package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.pojo.SqlCommandType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        //同时解析四种标签，并为mappedstatement对象添加相应的类型，用来在代理时区分使用不同的方法进行增强
        List<Element> queryList = rootElement.selectNodes("//select");
        for (Element element : queryList) {
            MappedStatement ms = setMappedStatement(element, SqlCommandType.SELECT);
            String key = namespace + "." + ms.getId();
            configuration.getMappedStatementMap().put(key, ms);
        }

        List<Element> updateList = rootElement.selectNodes("//update");
        for (Element element : updateList) {
            MappedStatement ms = setMappedStatement(element, SqlCommandType.UPDATE);
            String key = namespace + "." + ms.getId();
            configuration.getMappedStatementMap().put(key, ms);
        }

        List<Element> insertList = rootElement.selectNodes("//insert");
        for (Element element : insertList) {
            MappedStatement ms = setMappedStatement(element, SqlCommandType.INSERT);
            String key = namespace + "." + ms.getId();
            configuration.getMappedStatementMap().put(key, ms);
        }

        List<Element> deleteList = rootElement.selectNodes("//delete");
        for (Element element : deleteList) {
            MappedStatement ms = setMappedStatement(element, SqlCommandType.DELETE);
            String key = namespace + "." + ms.getId();
            configuration.getMappedStatementMap().put(key, ms);
        }
    }

    /**
     * @param element 标签元素
     * @param sqlCommandType sql类型
     * @return mappedStatement对象，包含id,parametertype,resulttype,sql，sql类型等属性
     */
    private MappedStatement setMappedStatement(Element element, SqlCommandType sqlCommandType) {
        String id = element.attributeValue("id");
        String resultType = element.attributeValue("resultType");
        String paramterType = element.attributeValue("paramterType");
        String sqlText = element.getTextTrim();
        MappedStatement mappedStatement = new MappedStatement();
        mappedStatement.setId(id);
        mappedStatement.setResultType(resultType);
        mappedStatement.setParamterType(paramterType);
        mappedStatement.setSql(sqlText);
        mappedStatement.setSqlCommandType(sqlCommandType);
        return mappedStatement;
    }


}
